﻿using Tiny.Imaging.Filter.PixelLibrary;

namespace Tiny.Imaging.Filter.PointFilter
{
    public struct ChannelMixerFactor
    {
        public float B, Constant;
        public float G;
        public float R;

        public ChannelMixerFactor(float r = 0, float g = 0, float b = 0, float c = 0)
        {
            R = r;
            G = g;
            B = b;
            Constant = c * 255;
        }
    }

    public class ChannelMixerFilter : BaseFilter.BaseFilter
    {
        public ChannelMixerFactor? RedChannel { get; set; }

        public ChannelMixerFactor? GreenChannel { get; set; }

        public ChannelMixerFactor? BlueChannel { get; set; }

        public override int Process(Rgba rgba)
        {
            Rgba result = new Rgba
                              {
                                  R = RedChannel.HasValue ? Mix(rgba, RedChannel.Value) : rgba.R,
                                  G = GreenChannel.HasValue ? Mix(rgba, GreenChannel.Value) : rgba.G,
                                  B = BlueChannel.HasValue ? Mix(rgba, BlueChannel.Value) : rgba.B
                              };

            return BlendRgba(rgba, result).ToInteger();
        }

        private int Mix(Rgba rgba, ChannelMixerFactor factor)
        {
            return MathLibrary.MathLibrary.Clamp((factor.R * rgba.R + factor.G * rgba.G + factor.B * rgba.B) + factor.Constant);
        }
    }
}